import DateSelectPopup, {
  ComplexDateSelectedValue,
  DateDefaultValue,
} from '@/components/date-range-selector';
import {
  DetailResult,
  PageResult,
  Study,
  WeiXinUser,
  type StudySearchStatsXTagCount
} from '@/pages/types/type';
import { checkAuthorize } from '@/utils/authorize';
import { getRequestInit, postRequestInit, urlPrefix } from '@/utils/http';
import { Content, Page } from '@alita/flow';
import { setPageNavBar, useModel, useNavigate } from 'alita';

import { useSearchParams } from 'alita';

import {
  Badge,
  Cascader,
  DatePicker,
  ErrorBlock,
  InfiniteScroll,
  Picker,
  PullToRefresh,
  SearchBar,
  Skeleton,
  Tag,
} from 'antd-mobile';
import classNames from 'classnames';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn'; // 导入本地化语言
import relativeTime from 'dayjs/plugin/relativeTime';
import React, { useEffect, useState } from 'react';
import styles from './index.less';
// import { UseAuthModel } from '@/models/useAuthModel';
dayjs.extend(relativeTime);
dayjs.locale('zh-cn');
let timer: any = null;
// 骨架屏组件
const StudyListSkeleton: React.FC = () => {
  return (
    <div className={styles.listItem}>
      <div className={styles.studyCard}>
        <div className={styles.cardHeader}>
          <div className={styles.titleSection}>
            <Skeleton.Paragraph
              lineCount={1}
              animated
              style={{ width: '140px', height: '20px', marginBottom: '8px' }}
            />
            <div
              className={styles.patientInfo}
              style={{ display: 'flex', gap: '8px' }}
            >
              <Skeleton.Paragraph
                lineCount={1}
                animated
                style={{ width: '50px', height: '16px' }}
              />
              <Skeleton.Paragraph
                lineCount={1}
                animated
                style={{ width: '30px', height: '16px' }}
              />
              <Skeleton.Paragraph
                lineCount={1}
                animated
                style={{ width: '60px', height: '16px' }}
              />
            </div>
          </div>
          <div className={styles.rightSection}>
            <Skeleton.Paragraph
              lineCount={1}
              animated
              style={{ width: '90px', height: '16px', marginBottom: '8px' }}
            />
            <Skeleton.Paragraph
              lineCount={1}
              animated
              style={{ width: '50px', height: '14px' }}
            />
          </div>
        </div>
        <div className={styles.companyInfo}>
          <Skeleton.Paragraph
            lineCount={1}
            animated
            style={{ width: '120px', height: '16px' }}
          />
          <Skeleton.Paragraph
            lineCount={1}
            animated
            style={{ width: '70px', height: '16px' }}
          />
        </div>
        <div className={styles.requirements}>
          <div
            style={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
            }}
          >
            <Skeleton.Paragraph
              lineCount={1}
              animated
              style={{ width: '160px', height: '16px' }}
            />
            <Skeleton.Paragraph
              lineCount={1}
              animated
              style={{ width: '50px', height: '16px' }}
            />
          </div>
        </div>
        <div className={styles.cardFooter}>
          <Skeleton.Paragraph
            lineCount={1}
            animated
            style={{ width: '100px', height: '14px' }}
          />
          <Skeleton.Paragraph
            lineCount={1}
            animated
            style={{ width: '80px', height: '14px' }}
          />
        </div>
      </div>
    </div>
  );
};

interface SearchParams {
  page: number;
  size: number;
  xTag: string;
  keyword?: string;
}

interface SearchOptoinsWapper {
  clinicalDepartments: {
    value: string;
    label: string;
    children?: { value: string; label: string }[];
  }[];
  diagnosisGroups: { value: string; label: string }[];
  ecgTypes: { value: string; label: string }[];
  lastLivingTypes: { value: string; label: string }[];
  testResultStatuses: { value: string; label: string }[];
  workingModes: { value: string; label: string }[];
}

const StudySearch: React.FC = () => {
  const navigate = useNavigate();
  const [searchKeyword, setSearchKeyword] = useState('');

  const [studyList, setStudyList] = useState<Study[]>([]);
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(false);
  const [tokening, setTokening] = useState<boolean>(true);
  const [tokenFail, setTokenFail] = useState<string | undefined>(undefined);
  const [authOK, setAuthOK] = useState<boolean>(false);
  const [isResetting, setIsResetting] = useState(false); // 新增：跟踪是否正在重置到第一页
  const [urlQueryParams, setUrlQueryParams] = useSearchParams();
  const [statsXTagCount, setTatsXTagCount] =
    useState<StudySearchStatsXTagCount>({
      leader: undefined,
      userPerspective: 'xxx',
      wrapper: {
        clinicalDepartments: undefined,
        hospitals: undefined,
        grp1: undefined,
        grp2: undefined,
        doctor: undefined,
        projectManager: false,
      },
      countItems: [],
    });

  const model = useModel('useAuthModel');

  const initXTag = urlQueryParams.get('xTag') || 'none';

  useEffect(() => {
    setPageNavBar({
      pagePath: location.pathname,
      navBar: {
        hideNavBar: true,
        pageTitle: `检查单`,
        pageBackground: '#eee',
      },
    });
    //console.log('已经设置了！');
    checkAuthorize(
      (x) => setTokening(x),
      (y) => {
        console.log(`token检查完成，是否通过授权：${y}`);
        setAuthOK(y);
      },
      (z) => setTokenFail(z),
      model,
    );
  }, []);

  const [searchParams, setSearchParams] = useState<SearchParams>({
    page: 0,
    size: 20,
    xTag: initXTag,
    keyword: undefined,
  });
  const [activeTab, setActiveTab] = useState(initXTag);

  // 筛选条件状态
  const [selectedStatus, setSelectedStatus] = useState<string>('');
  const [selectedDepartment, setSelectedDepartment] = useState<string[]>([]);
  const [selectedDiagnosisGroup, setSelectedDiagnosisGroup] =
    useState<string>('');
  const [selectedWorkingMode, setSelectedWorkingMode] = useState<string>('');
  const [date, setDate] = useState<ComplexDateSelectedValue>(DateDefaultValue);
  const [showDatePicker, setShowDatePicker] = useState<boolean>(false);
  const [showStatusPicker, setShowStatusPicker] = useState<boolean>(false);

  const [showDepartmentPicker, setShowDepartmentPicker] =
    useState<boolean>(false);
  const [showDiagnosisGroupPicker, setShowDiagnosisGroupPicker] =
    useState<boolean>(false);
  const [showWorkingModePicker, setShowWorkingModePicker] =
    useState<boolean>(false);
  // 审核状态：

  // 添加动态选项数据状态
  const [statusOptions, setStatusOptions] = useState<
    Array<{ label: string; value: string }>
  >([]);
  const [departmentOptions, setDepartmentOptions] = useState<Array<any>>([]);
  const [diagnosisGroupOptions, setDiagnosisGroupOptions] = useState<
    Array<{ label: string; value: string }>
  >([]);
  const [workingModeOptions, setWorkingModeOptions] = useState<
    Array<{ label: string; value: string }>
  >([]);

  const [tvis, setTvis] = useState<Array<{ value: string; label: string }>>([]);
  const [tvisVisable, setTvisVisable] = useState<boolean>(false);
  const [selectedTvis, setSelectedTvis] = useState<string>('');

  useEffect(() => {
    let response: Promise<Response> = fetch(
      `${urlPrefix}/api/study-search/get-study-search-params`,
      getRequestInit(),
    );
    response.then((rsp: Response) => {
      if (rsp.ok) {
        rsp.json().then(({ data, code }: DetailResult<SearchOptoinsWapper>) => {
          if (code === 0) {
            // 设置状态选项
            const {
              workingModes,
              lastLivingTypes,
              clinicalDepartments,
              diagnosisGroups,
              testResultStatuses,
            } = data!;
            if (testResultStatuses) {
              setTvis([{ label: '全部', value: '' }, ...testResultStatuses]);
            }
            if (workingModes) {
              setWorkingModeOptions([
                { label: '全部', value: '' },
                ...data!.workingModes,
              ]);
            }
            if (lastLivingTypes) {
              setStatusOptions([
                { label: '全部', value: '' },
                ...lastLivingTypes.map((item: any) => ({
                  label: item.name || item.label,
                  value: item.code || item.value,
                })),
              ]);
            }

            // 设置部门选项
            if (clinicalDepartments) {
              setDepartmentOptions([
                { label: '全部', value: '', children: [] },
                ...clinicalDepartments,
              ]);
            }

            // 设置诊断组选项
            if (diagnosisGroups) {
              setDiagnosisGroupOptions([
                { label: '全部', value: '' },
                ...diagnosisGroups.map((item: any) => ({
                  label: item.name || item.label,
                  value: item.code || item.value,
                })),
              ]);
            }
          }
        });
      }
    });
  }, []);

  function getTabNumber() {
    const response2: Promise<Response> = fetch(
      `${urlPrefix}/api/study-search/stats-x-tag-count`,
      getRequestInit(),
    );
    response2.then((rsp: Response) => {
      if (rsp.ok) {
        rsp
          .json()
          .then(
            ({
              data,
              code,
              msg,
            }: {
              data?: StudySearchStatsXTagCount;
              code: number;
              msg: string;
            }) => {
              if (code === 0) {
                setTatsXTagCount(data!);
              }
            },
          );
      }
    });
  }

  useEffect(() => {
    getTabNumber();
    timer = setInterval(() => {
      getTabNumber();
    }, 30000);
    return () => {
      clearInterval(timer);
    };
  }, []);

  useEffect(() => {
    checkAuthorize(
      (x) => setTokening(x),
      (y) => {
        console.log(`token检查完成，是否通过授权：${y}`);
        setAuthOK(y);
      },
      (z) => setTokenFail(z),
      model,
    );
  }, []);

  const tabs = statsXTagCount.countItems.map(
    ({ tab: { value, label }, count, color }) => ({
      key: value,
      title: (
        <Badge
          content={count}
          style={{
            '--right': '-6px',
            '--top': '0px',
            '--color': `var(--adm-badge-color, var(--adm-color-${
              count <= 0 ? 'weak' : color === 'default' ? 'success' : color
            }))`,
          }}
        >
          {label}
        </Badge>
      ),
    }),
  );

  useEffect(() => {}, []);

  // 获取列表数据
  const fetchStudyList = async (params: SearchParams, isRefresh = false) => {
    // 如果是刷新操作或者列表为空，允许显示loading状态
    if (loading && !isRefresh) return;

    setLoading(true);
    // 如果是重置到第一页，设置重置状态
    if (isRefresh && params.page === 0) {
      setIsResetting(true);
    }
    try {
      const requestParams = {
        ...params,
        keyword: searchKeyword || undefined,
        lastStudyLivingTypeStandard: selectedStatus || undefined,
        imageAcquisitionDateValue: date || undefined,
        hospitalOrClinicalDepartmentIds: selectedDepartment,
        diagnosisGroups: selectedDiagnosisGroup || undefined,
        workingMode: selectedWorkingMode || undefined,
        testResultStatus:selectedTvis ||undefined
      };

      const response = await fetch(
        `${urlPrefix}/api/study-search`,
        postRequestInit(requestParams),
      );

      if (response.ok) {
        const {
          data,
          code,
          msg,
          last,
          totalElements,
          totalPages,
        }: PageResult<Study> = await response.json();

        if (code === 0) {
          const newData = data || [];
          console.log(newData);
          if (isRefresh) {
            setStudyList(newData);
          } else {
            setStudyList((prev) => [...prev, ...newData]);
          }
          setHasMore(!last);
        }
      }
    } catch (error) {
      console.error('获取数据失败:', error);
    } finally {
      setLoading(false);
      setIsResetting(false); // 重置完成后清除重置状态
    }
  };

  // 搜索
  const handleSearch = () => {
    // 直接调用fetchStudyList，不更新searchParams
    fetchStudyList({ ...searchParams, page: 0, keyword: searchKeyword }, true);
  };

  // 标签页切换
  const handleTabChange = (key: string) => {
    setActiveTab(key);
    const newParams = { ...searchParams, page: 0, xTag: key };
    setSearchParams(newParams);
  };

  // 加载更多
  const loadMore = async () => {
    // 如果正在加载中，直接返回，防止重复调用
    if (loading) {
      console.log('loadMore已在执行中，跳过本次调用');
      return;
    }

    console.log('loadMore执行...');
    const newParams = { ...searchParams, page: searchParams.page + 1 };

    try {
      // 直接调用fetchStudyList，不更新searchParams，避免触发useEffect
      await fetchStudyList(newParams);
      // 只在成功加载后更新searchParams，用于状态同步
      setSearchParams(newParams);
    } catch (error) {
      console.error('加载更多失败:', error);
      // 失败时不更新searchParams，保持当前页码
    }
  };

  // 下拉刷新
  const onRefresh = async () => {
    const newParams = { ...searchParams, page: 0 };
    setSearchParams(newParams);
  };

  // 时间选择
  // 修正 handleDateChange 函数
  const handleDateChange = (dateValue: ComplexDateSelectedValue) => {
    setDate(dateValue);
    setShowDatePicker(false);
    const newParams = { ...searchParams, page: 0 };
    setSearchParams(newParams);
  };

  const getDepartmentLabel = (values: string[]) => {
    if (values.length === 0) return '';

    let currentOptions = departmentOptions;
    let labels: string[] = [];

    for (let i = 0; i < values.length; i++) {
      const value = values[i];
      if (value === '') {
        labels.push('全部');
        break;
      }

      const option = currentOptions.find((opt) => opt.value === value);
      if (option) {
        labels.push(option.label);
        if (option.children && i < values.length - 1) {
          currentOptions = option.children;
        }
      } else {
        break;
      }
    }

    return labels[labels.length - 1] || '';
  };

  // 组件初始化时获取数据
  useEffect(() => {
    if (authOK) {
      fetchStudyList(searchParams, true);
    }
  }, [authOK]);

  // 监听searchParams中非page字段的变化，自动触发数据获取
  useEffect(() => {
    if (authOK) {
      const { ...otherParams } = searchParams;
      // 只有当非page参数变化时才重新获取数据
      fetchStudyList({ ...otherParams, page: 0 }, true);
    }
  }, [
    searchParams.xTag,
    activeTab,
    selectedStatus,
    date,
    selectedDepartment,
    selectedDiagnosisGroup,
    selectedWorkingMode,
    selectedTvis
  ]);

  return (
    <Page>
      <Content>
        <div className={styles.studySearchContainer}>
          <div className={styles.filterGroup}>
            {/* 搜索区域 */}
            <div className={styles.searchSection}>
              <div className={styles.searchBarContainer}>
                <SearchBar
                  placeholder="患者姓名，身份证，医生姓名，工号" // 根据图片修改占位符文本
                  value={searchKeyword}
                  onChange={setSearchKeyword}
                  onSearch={handleSearch}
                  className={styles.searchBar}
                />
                <div
                  onClick={handleSearch}
                  color="primary"
                  style={{
                    borderLeft: '1px solid #eee',
                    paddingLeft: 10,
                    fontSize: 14,
                  }}
                >
                  搜索
                </div>
              </div>
            </div>

            {/* 标签页 */}
            <div className={styles.tabsGroup}>
              {tabs.map((tab) => (
                <div
                  onClick={() => handleTabChange(tab.key)}
                  className={classNames(styles.item, {
                    [styles.active]: activeTab === tab.key,
                  })}
                  key={tab.key}
                >
                  {tab.title}
                </div>
              ))}
            </div>

            {/* 筛选条件行 */}
            <div className={styles.filterRow}>
              <div
                className={styles.filterItem}
                onClick={() => setShowStatusPicker(true)}
              >
                <span className={styles.filterLabel}>状态:</span>
                <span className={styles.filterValue}>
                  {selectedStatus
                    ? statusOptions
                        .flat()
                        .find((opt) => opt.value === selectedStatus)?.label ||
                      ''
                    : '全部'}
                </span>
              </div>
              <div className={styles.line}></div>
              <div
                className={styles.filterItem}
                onClick={() => setShowDatePicker(true)}
              >
                <span className={styles.filterLabel}>检查时间:</span>
                <span className={styles.filterValue}>
                  {date.lastClick ? date.tip : '选择日期'}
                </span>
              </div>
              <div className={styles.line}></div>
              <div
                className={styles.filterItem}
                onClick={() => setTvisVisable(true)}

              >
                <span className={styles.filterLabel}>诊断结果:</span>
                <span className={styles.filterValue}>
                  {!selectedTvis
                    ? '全部'
                    : tvis.find(({ value }) => value === selectedTvis)?.label ||
                      ''}
                </span>
                <Picker
                  columns={[tvis]}
                  visible={tvisVisable}
                  onClose={() => setTvisVisable(false)}
                  value={selectedTvis ? [selectedTvis] : []}
                  onConfirm={(val) => {
                    setSelectedTvis((val[0] as string) || '');
                    setTvisVisable(false);
                    const newParams = { ...searchParams, page: 0 };
                    setSearchParams(newParams);
                  }}
                  title="选择状态"
                />
              </div>
              <div className={styles.line}></div>

              <div
                className={styles.filterItem}
                onClick={() => setShowDepartmentPicker(true)}
              >
                <span className={styles.filterLabel}>部门:</span>
                <span className={styles.filterValue}>
                  {getDepartmentLabel(selectedDepartment) || '全部'}
                </span>
              </div>
              <div className={styles.line}></div>
              <div
                className={styles.filterItem}
                onClick={() => setShowDiagnosisGroupPicker(true)}
              >
                <span className={styles.filterLabel}>诊断组:</span>
                <span className={styles.filterValue}>
                  {selectedDiagnosisGroup
                    ? diagnosisGroupOptions
                        .flat()
                        .find((opt) => opt.value === selectedDiagnosisGroup)
                        ?.label || ''
                    : '全部'}
                </span>
              </div>
              <div className={styles.line}></div>
              <div
                className={styles.filterItem}
                onClick={() => setShowWorkingModePicker(true)}
              >
                <span className={styles.filterLabel}>模式:</span>
                <span className={styles.filterValue}>
                  {workingModeOptions.find(
                    ({ value }) => value === selectedWorkingMode,
                  )?.label || '全部'}
                </span>
              </div>
            </div>
          </div>

          {/* 列表内容 */}
          <div className={styles.listContainer}>
            <PullToRefresh onRefresh={onRefresh}>
              {(loading && studyList.length === 0) || isResetting ? (
                // 首次加载或重置到第一页时显示骨架屏
                <div>
                  {Array.from({ length: 5 }).map((_, index) => (
                    <StudyListSkeleton key={`skeleton-${index}`} />
                  ))}
                </div>
              ) : studyList.length === 0 && !loading ? (
                <ErrorBlock status="empty" />
              ) : (
                <div>
                  {studyList.map((item, index) => {
                    const {
                      name,
                      idCardNo,
                      idCardType,
                      device,
                      clinicalDepartment,
                      diagnosisGroup,
                      doctor,
                      hospital,
                      ecgType,
                      lastLiving,
                      livingOfLastImpression,
                      livingOfCurrentDoing, // 当前正在进行的审核操作，不是诊断中，就是审核中，已诊断，已审核的不算。
                      age,
                      ageUnit,
                      workingMode,
                      testResultStatus,
                    } = item;
                    return (
                      <div
                        key={`${item.id}-${index}`}
                        className={styles.listItem}
                      >
                        <div
                          className={styles.studyCard}
                          // onClick={() => navigate(`/study/detail?id=${item.id}`)}
                          onClick={() => {
                            clearInterval(timer);
                            navigate(
                              `/study/diagnostic?id=${item.id}&code=${
                                item.code
                              }&name=${item.name}&other=${
                                item.name +
                                item.age +
                                '-' +
                                item.ageUnit.label +
                                '-' +
                                item.sex.label
                              }`,
                            );
                          }}
                          style={{ cursor: 'pointer' }}
                        >
                          {/* 卡片头部 */}
                          <div className={styles.cardHeader}>
                            <div className={styles.titleSection}>
                              <h3 className={styles.jobTitle}>{item.name}</h3>
                              <div className={styles.patientInfo}>
                                <Tag className={styles.tag} color="#f6f6f6">
                                  {item.age}({ageUnit.label})
                                </Tag>
                                <Tag className={styles.tag} color="#f6f6f6">
                                  {item.sex.label}
                                </Tag>
                                <Tag className={styles.tag} color="#f6f6f6">
                                  {ecgType.label}
                                </Tag>
                              </div>
                            </div>
                            <div className={styles.rightSection}>
                              <div
                                className={styles.urgencyTag}
                                style={{
                                  color: !testResultStatus
                                    ? '#478ff9'
                                    : testResultStatus.value === 'danger'
                                    ? '#ff3141'
                                    : testResultStatus.value === 'abnormal'
                                    ? '#ff8f1f'
                                    : '#1677ff',
                                }}
                              >
                                {livingOfLastImpression && (
                                  <>
                                    {
                                      livingOfLastImpression?.testResultStatus
                                        ?.label
                                    }
                                    (
                                    {
                                      livingOfLastImpression?.type.standard
                                        ?.label
                                    }
                                    )
                                  </>
                                )}
                              </div>
                              <div className={styles.leadInfo}>
                                {workingMode.value === 'Emergency' ? (
                                  <span style={{ color: 'red' }}>
                                    {workingMode.label}
                                  </span>
                                ) : (
                                  <>{workingMode.label}</>
                                )}
                              </div>
                            </div>
                          </div>

                          {/* 科室和医生信息 */}
                          <div className={styles.companyInfo}>
                            <span className={styles.companyName}>
                              {hospital.name}/{clinicalDepartment.name}
                            </span>
                            <span className={styles.doctorInfo}>
                              {doctor?.name || '无检查医生'}
                            </span>
                          </div>

                          {/* 检查信息标签 */}
                          {/* <div className={styles.requirements}>
                            <div
                              style={{ display: 'flex', alignItems: 'center' }}
                            >
                              <Avatar
                              src="https://images.unsplash.com/photo-1493666438817-866a91353ca9?ixlib=rb-0.3.5&q=80&fm=jpg&crop=faces&fit=crop&h=200&w=200&s=b616b2c5b373a80ffc9636ba24f7a4a9"
                              style={{
                                '--size': '28px',
                                '--border-radius': '50%',
                                marginRight: 6,
                              }}
                            />
                              {livingOfCurrentDoing && (
                                <>
                                  <span className={styles.name}>
                                    {livingOfCurrentDoing?.leader?.name} 5分钟前{' '}
                                  </span>
                                  <span className={styles.reqTag}>
                                    {livingOfCurrentDoing.type.standard.label}
                                  </span>
                                </>
                              )}
                            </div>
                            <div className={styles.group}>
                              {diagnosisGroup.name}
                            </div>
                          </div> */}

                          {/* 底部信息 */}
                          {/* <div className={styles.cardFooter}>
                            <div className={styles.deviceInfo}>
                              <span className={styles.deviceLabel}>设备:</span>
                              <span className={styles.deviceCode}>
                                {device.serialNumber}
                              </span>
                            </div>
                            <div className={styles.timeInfo}>
                              <span className={styles.timeLabel}>采集:</span>
                              <span className={styles.timeValue}>
                                {dayjs(item.imageAcquisition.start)
                                  .locale('zh-cn')
                                  .fromNow()}
                              </span>
                            </div>
                          </div> */}
                        </div>
                      </div>
                    );
                  })}
                </div>
              )}

              <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
            </PullToRefresh>
          </div>

          {/* 开始时间选择器 */}
          <DatePicker
            visible={showDatePicker}
            onClose={() => setShowDatePicker(false)}
            onConfirm={handleDateChange}
            title="受理时间"
          />

          {/* 状态选择器 */}
          <Picker
            columns={[statusOptions]}
            visible={showStatusPicker}
            onClose={() => setShowStatusPicker(false)}
            value={selectedStatus ? [selectedStatus] : []}
            onConfirm={(val) => {
              setSelectedStatus((val[0] as string) || '');
              setShowStatusPicker(false);
              const newParams = { ...searchParams, page: 0 };
              setSearchParams(newParams);
            }}
            title="选择状态"
          />

          {/* 部门选择器 */}
          <Cascader
            options={departmentOptions}
            visible={showDepartmentPicker}
            onClose={() => setShowDepartmentPicker(false)}
            value={selectedDepartment}
            onConfirm={(val) => {
              setSelectedDepartment(val as string[]);
              setShowDepartmentPicker(false);
              const newParams = { ...searchParams, page: 0 };
              setSearchParams(newParams);
            }}
            title="选择部门"
          />

          {/* 诊断组选择器 */}
          <Picker
            columns={[diagnosisGroupOptions]}
            visible={showDiagnosisGroupPicker}
            onClose={() => setShowDiagnosisGroupPicker(false)}
            value={selectedDiagnosisGroup ? [selectedDiagnosisGroup] : []}
            onConfirm={(val) => {
              setSelectedDiagnosisGroup((val[0] as string) || '');
              setShowDiagnosisGroupPicker(false);
              const newParams = { ...searchParams, page: 0 };
              setSearchParams(newParams);
            }}
            title="选择诊断组"
          />

          {/* 工作模式选择器 */}
          <Picker
            columns={[workingModeOptions]}
            visible={showWorkingModePicker}
            onClose={() => setShowWorkingModePicker(false)}
            value={selectedWorkingMode ? [selectedWorkingMode] : []}
            onConfirm={(val) => {
              setSelectedWorkingMode((val[0] as string) || '');
              setShowWorkingModePicker(false);
              const newParams = { ...searchParams, page: 0 };
              setSearchParams(newParams);
            }}
            title="选择模式"
          />
        </div>
        <DateSelectPopup
          visable={showDatePicker}
          dateSelectedValue={date}
          hide={setShowDatePicker}
          setDateSelectedValue={setDate}
        />
      </Content>
    </Page>
  );
};

export default StudySearch;
